<template>
  <el-row class='organization-container'>
    <!-- 左侧组织树 -->
    <el-col :span="6"
            class="left-tree-style">
      <div class="adminBtn">
        <el-button type="primary"
                   size="medium"
                   @click="lookAdmin">查看管理员</el-button>
      </div>
      <OrganizationTree :assignedNode.sync="assignNode"
                        :treeHeight.sync="treeHeight"
                        :assignedTemplateNode.sync="assignTemplateNode"
                        :assignedPermissionNode.sync="assignPermissionNode"
                        :curMenu.sync="selectedNode"></OrganizationTree>
    </el-col>
    <!-- <el-col :span="2">
     
    </el-col> -->
    <el-col :span="18">
      <!-- 右侧内容区，包含权限清单及人员列表tab -->
      <el-tabs type="border-card"
               class="unit_tabs">
        <el-tab-pane label="权限清单">
          <!-- <el-tabs type="card"
                   class="Permiss">
            <PermissionTemplateList ref="permissionList"
                                    :requestParam="getJobPermissionListParam"></PermissionTemplateList>
          </el-tabs> -->
          <el-row class="table-container"
                  style="margin-bottom:15px;">
            <el-col class="table-content"
                    :span="24">
              <el-table ref="clearTable"
                        :highlight-current-row="true"
                        :header-cell-style="{background:'#f5f5f5'}"
                        :data="jobPermissionList.list"
                        border
                        class="obs-style">
                <el-table-column type="index"
                                 label="序号"
                                 sortable
                                 align="center"
                                 width="100"
                                 show-overflow-tooltip>
                </el-table-column>
                <el-table-column prop="system_name"
                                 label="所属应用"
                                 align="center"
                                 show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="权限名称"
                                 prop="object_name"
                                 align="center"
                                 show-overflow-tooltip>
                </el-table-column>

                <el-table-column label="操作"
                                 align="center">
                  <template slot-scope="scope">
                    <el-button width="80px"
                               v-if="scope.row.job_object_rela_id !== null"
                               size="mini"
                               @click="jobPerDeleteConfirm(scope)"
                               type="text">
                      删除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
            <el-col :span="24"
                    align="center"
                    style="margin-bottom:20px;">
              <el-pagination background
                             id="obs_page"
                             @size-change="handlelookSizeChange"
                             @current-change="handleCurrentChange"
                             :current-page="getJobPermissionListParam.page"
                             :page-size="getJobPermissionListParam.page_size"
                             :page-sizes="[10]"
                             layout="total,sizes,prev, pager, next, jumper"
                             :total="jobPermissionList.total_count">
              </el-pagination>
            </el-col>
          </el-row>
        </el-tab-pane>
        <!-- 轻应用权限 -->
        <el-tab-pane label="轻应用权限">
          <el-row style="margin-bottom:15px"
                  class="table-container11">
            <el-col :span="24">
              <el-table ref="obsTable"
                        :highlight-current-row="true"
                        :header-cell-style="{background:'#f5f5f5'}"
                        :data="applimit.list"
                        border
                        height="280"
                        class="obs-style">
                <el-table-column prop="app_name"
                                 label="轻应用名称"
                                 align="center"
                                 show-overflow-tooltip>
                </el-table-column>
                <el-table-column label="操作"
                                 align="center">
                  <template slot-scope="scope">
                    <el-button width="80px"
                               size="mini"
                               @click="appLimitDeleteConfirm(scope.row)"
                               type="text">
                      移除
                    </el-button>
                  </template>
                </el-table-column>
              </el-table>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24"
                    align="center"
                    style="margin-bottom:20px;">
              <el-pagination background
                             id="obs_page"
                             @size-change="handleAppSizeChange"
                             @current-change="handleAppCurrentChange"
                             :current-page="getAppLimitParam.page"
                             :page-sizes="[10]"
                             layout="total,sizes,prev, pager, next, jumper"
                             :page-size="getAppLimitParam.page_size"
                             :total="applimit.total_count">
              </el-pagination>
            </el-col>
          </el-row>
        </el-tab-pane>

        <el-tab-pane label="人员列表">
          <JobUserList ref="jobUserList"
                       :requestParam="getJobUserListParam"></JobUserList>
        </el-tab-pane>
        <el-tab-pane label="详情">
          <el-tabs type="card"
                   class="Permiss">
            <div v-if="qrType === '2' || qrType === '1'">
              <UnitDetails :newDetailParam="detailParam"></UnitDetails>
            </div>
            <el-empty v-else
                      description="暂无数据"></el-empty>
          </el-tabs>
        </el-tab-pane>
      </el-tabs>
    </el-col>
    <!-- 分配人员列表弹框 -->
    <AssignUserListDialog @callback="assignUserCallback"
                          :dialogVisible.sync="assignUserDialogVisible"
                          :requestParam.sync="assignUserDialogParams"></AssignUserListDialog>
    <!-- 分配模板列表弹框 -->
    <AssignTemplateDialog @callback="assignTemplateCallback"
                          :dialogVisible.sync="assignTemplateDialogVisible"
                          :requestParam.sync="assignTemplageDialogParams"></AssignTemplateDialog>
    <!-- 分配权限列表弹框 -->
    <el-dialog title="分配权限"
               width="50%"
               :close-on-click-modal="false"
               :visible.sync="assignPermissionVisible">
      <AssignTemplate :showCheckbox="false"
                      :isVisible="assignPermissionVisible"
                      :curPermissionIds.sync="assignPermissionIds"></AssignTemplate>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="assignPermissionVisible=false">取消</el-button>
        <el-button @click="assignPermission"
                   type="primary">确定</el-button>
      </div>
    </el-dialog>

    <el-dialog title="查看管理员"
               width="60%"
               :visible.sync="lookAdminDialogVisible">
      <el-table ref="obsTable"
                :highlight-current-row="true"
                :header-cell-style="{background:'#f5f5f5'}"
                :data="adminData.list"
                border
                height="280"
                class="obs-style">
        <el-table-column type="index"
                         label="序号"
                         sortable
                         align="center"
                         width="100"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="user_no"
                         label="管理员账号"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="user_name"
                         label="用户名称"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
        <el-table-column prop="user_type"
                         label="类型"
                         align="center"
                         show-overflow-tooltip>
          <template slot-scope="scope">
            <p>{{scope.row.user_type === "1" ? "单位管理员" : "项目管理员"}}</p>
          </template>
        </el-table-column>
        <el-table-column prop="project_name"
                         label="项目名称"
                         align="center"
                         show-overflow-tooltip>
        </el-table-column>
      </el-table>
      <el-pagination id="pagination"
                     background
                     @current-change="handleAdminSizeChange"
                     :current-page="lookrequestParam.page"
                     :page-size="lookrequestParam.page_size"
                     layout="total, prev, pager, next, jumper"
                     :total="adminData.total_count">
      </el-pagination>
      <div slot="footer"
           class="dialog-footer">
        <el-button @click="lookAdminDialogVisible=false">取消</el-button>
        <el-button @click="lookAdminDialogVisible=false"
                   type="primary">确定</el-button>
      </div>
    </el-dialog>
  </el-row>
</template>
<script>

import AssignTemplate from '@/components/MenuTree/AssignTemplate'
import OrganizationTree from '@/components/OrganizationTree/OrganizationTree'
import UnitDetails from './components/UnitDetails'
import PermissionTemplateList from './components/PermissionTemplateList'
import JobUserList from './components/JobUserList'
import AssignUserListDialog from './components/AssignUserListDialog'
import AssignTemplateDialog from './components/AssignTemplateDialog'
import { organizationApi } from '@/services/CompanySetting'
import { permissionApi } from '@/services/CompanySetting'
export default {
  data () {
    return {
      treeHeight: '100%',
      lookrequestParam: {
        is_page: 1,
        page: 1,
        page_size: 10
      },
      assignPermissionIds: [], // 选中的权限编号
      //查看管理员
      lookAdminDialogVisible: false,
      adminData: {
        list: [],
        total_count: 0,
        total_page: 0
      }, //管理员列表
      // 当前选择的组织树节点数据
      selectedNode: {},
      //轻应用权限列表
      applimit: {
        list: [],
        total_count: 0,
        total_page: 0
      },
      //轻应用权限请求参数
      getAppLimitParam: {
        job_id: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },
      // 获取岗位权限清单列表参数
      getJobPermissionListParam: {
        job_id: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },
      // 岗位权限清单列表
      jobPermissionList: {
        list: [],
        total_count: 0,
        total_page: 0
      },
      //详情参数
      detailParam: {
        node_type: '',
        id: '',
      },
      // 当前选择节点
      currentNode: {},
      // 获取人员列表请求参数
      getJobUserListParam: {
        company_id: '',
        org_no: '',
        dept_no: '',
        job_id: '',
        node_type: '',
        user_name: '',
        is_page: 1,
        page: 1,
        page_size: 10
      },

      // 人员列表
      jobUserList: {
        list: [],
        total_count: 0,
        total_page: 0
      },
      // 分配人员列表弹框请求参数
      assignUserDialogParams: {},
      // 分配人员列表弹框是否可见
      assignUserDialogVisible: false,
      // 右键分配人员时选中的节点
      assignNode: {},
      // 右键分配权限时选中的节点
      assignPermissionNode: {},
      // 右键分配模板时选中的节点
      assignTemplateNode: {},
      // 分配权限模板弹框请求参数
      assignTemplageDialogParams: {

      },
      // 分配权限弹框是否可见
      assignPermissionVisible: false,
      // 分配模板弹框是否可见
      assignTemplateDialogVisible: false,
      qrType: "", //单位还是部门
      jobId: '', //岗位id 
    }
  },
  components: {
    OrganizationTree,
    PermissionTemplateList,
    JobUserList,
    AssignUserListDialog,
    AssignTemplateDialog,
    AssignTemplate,
    UnitDetails
  },
  watch: {
    // 组织树选择节点时，根据节点类型获取权限清单及人员列表
    selectedNode: {
      handler (newval, oldval) {
        this.qrType = newval.node_type //是单位还是部门,1是单位,2是部门
        let tempData = {}
        let detailData = {}

        tempData.node_type = newval.node_type
        tempData.user_name = ''
        detailData.node_type = newval.node_type
        detailData.id = newval.id
        tempData.company_id = newval.company_id;
        if (newval.node_type === '1') {
          //详情参数
          detailData.node_type = newval.node_type
          detailData.id = newval.id
          tempData.org_no = newval.org_no
          tempData.dept_no = '';
          tempData.job_id = '';
        } else if (newval.node_type === '2') {
          tempData.job_id = newval.id  //部门,岗位都要获取id
          //详情参数
          detailData.node_type = newval.node_type
          detailData.id = newval.id
          tempData.dept_no = newval.no
          tempData.org_no = newval.parent_no
        } else if (newval.node_type === '3') {
          tempData.job_id = newval.id
          tempData.dept_no = newval.parent_no
          this.getJobPermissionListParam.job_id = newval.id

          this.getAppLimitParam.job_id = newval.id
          this.getJobPermissionList()
          this.getLightappList()
        }
        this.getJobUserListParam = Object.assign(this.getJobUserListParam, tempData)
        this.detailParam = JSON.stringify(detailData)
        // console.log(this.detailParam, 'watch')
      },
      deep: true
    },
    // 在岗位节点上选择分配人员菜单时，触发分配人员弹框 
    assignNode: {
      handler (newval, oldval) {
        // console.log(newval, 'assign node')
        if (newval.id) {
          this.assignUserDialogParams = newval
          this.assignUserDialogVisible = true
        }
      },
      deep: true
    },
    assignUserDialogVisible (newval, oldval) {
      if (!newval) {
        this.assignNode = {}
      }
    },
    // 在岗位节点上分配人员权限模板时，出发分配权限弹框   右键传回来的节点数据
    assignTemplateNode: {
      handler (newval, oldval) {
        // console.log(newval, 'assign template node')
        if (newval.id) {
          this.assignTemplageDialogParams = newval
          this.assignTemplateDialogVisible = true
        }
      },
      deep: true
    },
    assignTemplateDialogVisible (newval, oldval) {
      if (!newval) {
        this.assignTemplateNode = {}
      }
    },
    //分配权限
    assignPermissionVisible (newval, oldval) {
      console.log(newval);
      if (!newval) {
        this.assignPermissionNode = {}
      }
    },
    assignPermissionNode: {
      handler (newval) {
        if (newval.id) {
          this.assignPermissionVisible = true
          this.jobId = newval.id  //获取岗位id
          console.log(this.jobId);
        }
      },
      deep: true
    },

  },
  methods: {
    // 删除权限清单确认弹框
    jobPerDeleteConfirm (scope) {
      this.$confirm('是否删除该权限清单？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        organizationApi.deleteJobPermission({
          data: {
            job_object_rela_id: scope.row.job_object_rela_id
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除权限清单成功')
            this.getJobPermissionList()
          }
        })
      })
    },
    // 获取岗位权限清单列表数据
    getJobPermissionList () {
      organizationApi.getJobList({
        params: this.getJobPermissionListParam
      }).then(res => {
        // console.log(res, 'get jpb permission list')
        if (res.code === 0) {
          this.jobPermissionList = res.data
        }
      })
    },
    //获取轻应用列表
    getLightappList () {
      organizationApi.getLightappList({
        params: this.getAppLimitParam
      }).then(res => {
        if (res.code === 0) {
          this.applimit = res.data
        }
      })
    },
    // 权限清单 ->值改变添加背景色
    handleClearChange (val) {
      this.currentRowNext = val
    },
    //查看管理员
    lookAdmin () {
      this.lookAdminDialogVisible = true
      organizationApi.getAdminList({
        params: this.lookrequestParam
      }).then(res => {
        if (res.code === 0) {
          this.adminData = res.data
        }
      })
    },
    //权限清单分页
    handlelookSizeChange () {
      this.getJobPermissionListParam.page_size = page
      this.getJobPermissionList()
    },
    //权限清单分页
    handleCurrentChange (page) {
      this.getJobPermissionListParam.page = page
      this.getJobPermissionList()
    },
    //查看管理员分页
    handleAdminSizeChange (page) {
      this.lookrequestParam.page = page
      this.lookAdmin()
    },
    //轻应用权限-每页条数
    handleAppSizeChange (page) {
      this.getAppLimitParam.page_size = page
      this.getLightappList()
    },
    //轻应用权限-页码
    handleAppCurrentChange (page) {
      this.getAppLimitParam.page = page
      this.getLightappList()
    },
    //轻应用权限-移除按钮
    appLimitDeleteConfirm (row) {
      this.$confirm('是否删除该权限清单？', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        organizationApi.deleteAppList({
          data: {
            job_id: row.job_id,
            app_id: row.app_id
          }
        }).then(res => {
          if (res.code === 0) {
            this.$message.success('删除轻应用成功')
            this.getLightappList()
          }
        })
      })
    },
    // 获取组织树数据
    getOrgTree () {
      organizationApi.getOrgTree({

      }).then(res => {
        // console.log(res, 'get org tree')
        let data = res.data
        this.$store.dispatch('setOrgainzationTree', data)
        window.localStorage.setItem('platformOrganizationTree', JSON.stringify(data))
      }, err => {
        console.log(err)
      })
    },
    // 处理数据，将depts、orgs、jobs数组统一放到childr_list字段中
    handleData (list) {
      // console.log(list, 'list')
      if (list && list.length > 0) {
        list.map((item) => {
          if (item.depts && item.depts.length > 0) {
            item.children_list = item.children_list.concat(item.depts)
          }
          if (item.jobs && item.jobs.length > 0) {
            item.children_list = item.children_list.concat(item.jobs)
          }
          this.handleData(item.children_list)
        })
      }
    },
    // 获取权限树数据
    getPermissionTreeData () {
      permissionApi.getPermissionTree({
        data: {
          type: 'dir'
        }
      }).then(res => {
        this.permissionTreeData = res.data
        this.$store.dispatch('setPermissionTree', this.permissionTreeData)
        window.localStorage.setItem('permissionTree', JSON.stringify(this.permissionTreeData))
      })
    },
    // 为当前行的模板分配权限---确定按钮被触发的事件
    assignPermission (scope) {
      let ids = []
      if (this.assignPermissionIds.length > 0) {
        this.assignPermissionIds.map((item) => {
          ids.push(item.object_id)
        })
        organizationApi.saveAssignPermission({
          data: {
            job_id: this.jobId,
            object_ids: ids.join(',')
          }
        }).then(res => {
          if (res.msg == 'SUCCESS') {
            this.assignPermissionVisible = false
            this.$message.success('添加成功！')
            this.getJobPermissionList()
          }
        }, err => {
          console.log(err)
        })
      } else {
        this.$message('请先勾选需要分配的权限!')
      }
    },
    // 分配人员列表成功回调
    assignUserCallback () {
      this.$refs.jobUserList.getUserList()
    },
    // 分配模板列表成功回调
    assignTemplateCallback () {
      this.$refs.permissionList.getJobPermissionList()
    }

  },
  created () {
    this.getOrgTree()
    this.getPermissionTreeData()
  },
  mounted () {
  }
}
</script>
<style scoped lang='scss'>
.left-tree-style {
  // overflow-y: auto;
  // display: flex;
  // position: relative;
  /deep/ .el-input {
    width: 60%;
  }
  .adminBtn {
    float: right;
    width: 40%;
    .el-button {
      margin-left: 15%;
    }
  }
}
.organization-container {
  padding: 20px;
  // padding: 20px;
  //display: flex;
  .organization-tree-container {
    margin-right: 20px;
  }
  .job-permission-table {
    flex-grow: 1;
  }
}
</style>
